var language = {
    "sProcessing": "处理中...",
    "sLengthMenu": "每页 _MENU_ 项",
    "sZeroRecords": "没有匹配结果",
    "sInfo": "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项。",
    "sInfoEmpty": "当前显示第 0 至 0 项，共 0 项",
    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
    "sInfoPostFix": "",
    "sSearch": "搜索:",
    "sUrl": "",
    "sEmptyTable": "表中数据为空",
    "sLoadingRecords": "载入中...",
    "sInfoThousands": ",",
    "oPaginate": {
        "sFirst": "首页",
        "sPrevious": "上页",
        "sNext": "下页",
        "sLast": "末页",
        "sJump": "跳转"
    },
    "oAria": {
        "sSortAscending": ": 以升序排列此列",
        "sSortDescending": ": 以降序排列此列"
    }
}
var myTables;

function initTables(url, columns, operate) {
    myTables = $('#dataTables').DataTable({
        language: language,
        autoWidth: false,  //禁用自动调整列宽
        processing: true,  //隐藏加载提示,自行处理
        serverSide: true,  //启用服务器端分页
        searching: true,  //禁用原生搜索
        orderMulti: false,  //启用多列排序
        order: [],  //取消默认排序查询,否则复选框一列会出现小箭头
        renderer: "bootstrap",  //渲染样式：Bootstrap和jquery-ui
        "pagingType": "full_numbers",
        "columns": columns,
        "aoColumnDefs": [{//倒数第一列
            "targets": -1,
            "bSortable": false,
            render: function (data, type, row) {
                if (operate) {
                    return operate;
                } else {
                    return '<a class="btn btn-xs tbEdit btn-warning" value="' + row.id + '">编辑</a>&nbsp;&nbsp;&nbsp;&nbsp;'
                        + '<a class="btn btn-xs btn-danger tbDelete" value="' + row.id + '">删除</a>';
                }
            }
        }],
        ajax: function (data, callback) {
            //封装请求参数
            var param = {};
            param.rows = data.length; //页面显示记录条数，在页面显示每页显示多少项的时候
            param.page = (data.start / data.length) + 1;//当前页码

            var $search = data.search.value;
            if ($search) {
                var s = JSON.parse($search);
                Object.assign(param, s);
            }
            if (data.order.length > 0) {
                param.order = data.columns[data.order[0].column].data;
                param.orderDir = data.order[0].dir;
            }
            $.ajax({
                type: "GET",
                url: baseUrl + url,
                cache: false,  //禁用缓存
                data: param,  //传入组装的参数
                dataType: "json",
                success: function (result) {
                    //setTimeout仅为测试延迟效果
                    setTimeout(function () {
                        //封装返回数据
                        const returnData = {};
                        returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                        returnData.recordsTotal = result.total;//返回数据全部记录
                        returnData.recordsFiltered = result.total;//后台不实现过滤功能，每次查询均视作全部结果
                        returnData.data = result.records;//返回的数据列表
                        callback(returnData);
                    }, 200);
                }
            });
        }
    });
}

$(document).ready(function () {
    $('#dataTables').on('click', '.tbEdit', function () {
        var data = myTables.row($(this).parents('tr')).data();

        var editUrl = $('#editUrl').val();
        var str = '?';
        if (editUrl.indexOf('?') > -1) {
            str = '&';
        }
        editUrl += str + 'id=' + data.id;
        location.href = baseUrl + editUrl;
        /*layer.open({
            type: 2,
            title: '修改',
            shadeClose: true,
            shade: 0.8,
            area: ['90%', '90%'],
            content: baseUrl + editUrl //iframe的url
        });*/
    }).on('click', '.tbDelete', function () {
        var data = myTables.row($(this).parents('tr')).data();
        var deleteUrl = $('#deleteUrl').val();
        if (!deleteUrl) {
            return;
        }
        layer.confirm('确认删除吗？', {
            btn: ['确认', '取消'], //按钮
            shade: false //不显示遮罩
        }, function () {
            var row = myTables.row($(this).parents('tr'));
            $.post(baseUrl + deleteUrl, {id: data.id}, function (result) {
                if (result.code == 0) {
                    layer.msg('删除成功');
                    row.remove().draw();
                } else {
                    layer.msg('删除失败');
                }
            })
        }, function () {
            layer.close();
        });
    });

    $('#addObject').on('click', function () {
        var addUrl = $('#addUrl').val();
        location.href = baseUrl + addUrl;
        /*layer.open({
            type: 2,
            title: '增加',
            shadeClose: true,
            shade: 0.8,
            area: ['90%', '90%'],
            content: baseUrl + addUrl //iframe的url
        });*/
    })
});

function closeLayer() {
    var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    parent.layer.close(index);
    var tables = parent.$("#dataTables").DataTable();
    tables.ajax.reload();
}

// urlEncode
var urlEncode = function (param, key, encode) {
    if (param == null) return '';
    var paramStr = '';
    var t = typeof (param);
    if (t == 'string' || t == 'number' || t == 'boolean') {
        paramStr += '&' + key + '=' + ((encode == null || encode) ? encodeURIComponent(param) : param);
    } else {
        for (var i in param) {
            var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
            paramStr += urlEncode(param[i], k, encode)
        }
    }
    return paramStr;

}